/*******************************************************************************
 * (c) Copyright 2017 lvxi. All Rights Reserved.
 ******************************************************************************/

/**
 * Created by lvxi on 2017/2/25.
 */
var ctx= window.location.protocol + '//' + window.location.host;
/********************************DOM相关begin************************************************/
function toggleShow(select) {
    var $rms = $(select);
    $rms.is(":visible") && $rms.hide()|| $rms.show() ;
}
/********************************DOM相关end************************************************/

/********************************弹窗处理相关begin************************************************/
/**
 * 错误提示
 * @param msg
 * @param t 可选  等到时间关闭
 * @param fn 可选 关闭后调用的方法
 * @param params 可选 layer参数
 */
function errorTipBox(msg, t,fn,params) {
    if(msg==null || msg.length==0) return;
    if( typeof t == 'function') fn=t;
    if (!t || typeof t != 'number' ) t = 3000;
    var parmsObj ={time: t, icon: 5,zIndex:99999900,shadeClose: true};
    if(params) $.extend(parmsObj,params);
    layer.msg(msg,parmsObj ,fn);
}
/**
 * 成功提示
 * @param msg
 * @param t 可选  等到时间关闭
 * @param fn 可选 关闭后调用的方法
 * @param params 可选 layer参数
 */
function successTipBox(msg, t,fn,params) {
    if(msg==null || msg.length==0) return;
    if( typeof t == 'function') fn=t;
    if (!t || typeof t != 'number' ) t = 3000;
    var parmsObj={time: t,zIndex:99999900 , icon: 6,shadeClose: true};
    if(params) $.extend(parmsObj,params);
    layer.msg(msg,parmsObj ,fn);
}

/********************************弹窗处理相关end************************************************/


/********************************表单处理相关begin************************************************/

function disableSubmitBtn() {
    $(".btn-submit").attr({ disabled: "disabled" });
}
function enableSubmitBtn() {
    $(".btn-submit").removeAttr("disabled");
}

var LAYER_LOAD;
function openLoadLayer(){
    disableSubmitBtn();
    LAYER_LOAD = layer.load(1, {
        shade: [0.3,'#fff'] //0.1透明度的白色背景
    });
}
function closeLoadLayer () {
    layer.close(LAYER_LOAD);
    LAYER_LOAD=null;
    enableSubmitBtn();
}


/**
 * 校验表单
 * @param formSelect  表单 选择器或 jquery对象
 * @returns {*|Boolean}
 */
function checkForm(formSelect) {
    formSelect = $(formSelect);
    var vlt = formSelect.data('bootstrapValidator');
    vlt.validate();
    return vlt.isValid();
}
/**
 * 表单
 * @param fn 可选调用方法
 */
function formAutoSubmit(formSelect,fn) {
    formSelect = $(formSelect);
    formSelect.find("input:text,input:password").each(function () {
        $(this).on('keypress',  //所有input标签回车无效
            function(e){
                var key = window.event ? e.keyCode : e.which;
                if(key.toString() == "13"){
                   if(fn==null) formSelect.find(".btn-submit").click();
                    else fn();
                    return false;
                }
            }
        );
    });
}

/**
 *ajax提交表单，
 * paramObj其中url不填则取表单中的action，type不填则取method，data不填则序列化表单
 * @param formSelect  表单 选择器或 jquery对象
 * @param paramObj ajax参数
 *        paramObj.check 提交前是否校验表单输入合法性 ，默认true
 *        paramObj.suberror ajax请求成功，但是服务器返回标示失败
 *        paramObj.success ajax请求成功，写了则suberror和subsuccess无效
 *        paramObj.subsuccess ajax请求成功，但是服务器返回标示成功
 *
 */
function ajaxSubmitForm(formSelect,paramObj) {

    formSelect = $(formSelect);
    if(formSelect==null) return;

    if((paramObj.check==undefined || paramObj.check) && !checkForm(formSelect)) return;
    var layerLoad;
    //默认配置开始
    var param ={
        closeMask:true, //subsuccess是否自动关闭遮罩层

        beforeSend:function (xhr) {
            //禁止表单重复提交
            openLoadLayer();
            return true;
        },complete:function(xhr,textStatus){
            var data = xhr.responseJSON;
            if(data!=undefined){
                if(data.status){
                    if(this.closeMask){
                        closeLoadLayer();
                    }
                }else {
                    closeLoadLayer();
                }
            }else {
                closeLoadLayer();
            }
        },error:function (xhr, textStatus, errorThrown) {
            errorTipBox(textStatus+"请求失败，请联系管理员");
        },
        success:function (data,textStatus) {
            if (data.status ) {
                if(paramObj.subsuccess) paramObj.subsuccess(data,textStatus);
            }else if(typeof data.status =='boolean' ) {
                if(data.CRSFToken!=undefined){
                    for(id in data.CRSFToken){
                        $("#"+id).val(data.CRSFToken[id]);
                    }
                }
                if(data.code=="1"){
                    vaildFormFields(formSelect,data.fields);
                    if(paramObj.suberror) paramObj.suberror(data,textStatus);
                    return;
                }
                if(paramObj.suberror) paramObj.suberror(data,textStatus);
                else{
                    var tip ="请求失败，请检查填写的数据";
                    if(data.msg!=undefined){
                        tip=data.msg;
                    }
                    errorTipBox(tip);
                }

            }

        }

    };
    $.extend(param,paramObj);
    //默认配置结束
    if(param.url==undefined) param.url = formSelect.attr("action");
    if(param.type==undefined) param.type= formSelect.attr("method").toUpperCase();
    if(param.data==undefined) param.data=formSelect.find(":not(.not-submit)").serialize();
    $.ajax(param);
}

function ajaxSubmit(paramObj) {
    //默认配置开始
    if(paramObj==null || paramObj==undefined){
        var paramObj = new Object();
    }

    if(typeof paramObj.async !='boolean') paramObj.async=true;

    if(typeof paramObj.beforeDo != 'function' ){

        paramObj.beforeDo = function (data,textStatus) {

            return true;
        };
    }

    if(typeof paramObj.finalDo != 'function' ){

        paramObj.finalDo = function (data,textStatus) {

        };
    }

    if(typeof paramObj.error != 'function' ){
        paramObj.error = function (XMLHttpRequest, textStatus, errorThrown) {
            errorTipBox(textStatus+"请求失败，请联系管理员");

        };
    }
    if(typeof paramObj.suberror != 'function' ){
        paramObj.suberror = function (data,textStatus) {
            errorTipBox("服务器返回错误，请求失败");

        };
    }
    if(typeof paramObj.success != 'function' ){

        if(typeof paramObj.subsuccess != 'function'){
            paramObj.subsuccess = function (data,textStatus) {

            };
        }

        paramObj.success = function (data,textStatus) {
            //successTipBox("请求成功");
            paramObj.subsuccess(data,textStatus);
        };
    }
    //默认配置结束


    $.ajax({
        cache: true,
        type: paramObj.method,
        url: paramObj.url,
        data: paramObj.data,
        async: paramObj.async,
        beforeSend: paramObj.beforeDo,
        error:  function(){
            paramObj.error
            paramObj.finalDo();
        },
        success:  function (data,textStatus) {
            if (data.status) {
                paramObj.success(data,textStatus);
            }else if(typeof data.status =='boolean' ) {
                paramObj.suberror(data,textStatus);
            }
            paramObj.finalDo();
        }
    });
}

/**
 * 通过for属性筛选,给必填的label标上星号
 * @param labelForSelect
 */
function addLabelStar(labelForSelect) {
    if( typeof labelForSelect == 'string') {
        var select ='label[for='+labelForSelect+']';
        labelForSelect = $(select);
    }
    if(labelForSelect==null) return;
    labelForSelect.each(function () {
        var labelHtml = $(this).html();
        if(labelHtml.indexOf('label-star')<0) {
            $(this).html("<strong><span  class='label-star'>*</span></strong>" + labelHtml);
        }
    });
}

/**
 * 为表单必填的label加上*号
 * @param formSelect 表单 选择器或 jquery对象
 */
function addFormLabelStar(formSelect) {
    formSelect = $(formSelect);

    if(formSelect==null) return;
    formSelect.each(function(){
        var form = $(this);
        form.find("small[data-bv-validator='notEmpty']").each(function () {
            var name = $(this).data('bv-for');
            var id = form.find('input[name='+name +'],textarea[name='+name +']').attr('id');
            addLabelStar(id);
        })

        form.find("input[required],textarea[required]").each(function () {
            var id = $(this).attr('id');
            addLabelStar(id);
        })

    });

}

/**
 * 校验表单的字段
 * @param formSelect 表单 选择器或 jquery对象
 * @param fields 数组 字段name名称
 */
function vaildFormFields(formSelect,fields) {
    formSelect = $(formSelect);
    if(formSelect==null) return;
    formSelect.each(function() {
        var form = $(this);
        var vlt = form.data('bootstrapValidator');
        for(var i=0;i<fields.length;i++){
            vlt.validateField(fields[i]);
        }
    });
}


/**
 * 数据ajax后台在线校验
 * @param formSelect 表单选择
 * @param name 校验的input name
 * @param url 后台校验地址
 * @param opts 对象，
 *        opts.method   ajax请求方式，get默认
 *        opts.validReturnValue  后台返回的合法的值，合法校验
 *        opts.message  校验失败提示消息
 */
function validateFieldOnline(formSelect, name, url, opts) {
    formSelect = $(formSelect);
    if (formSelect == null) return;

    if (opts == null) opts = new Object();

    if (opts.method == null) opts.method = "get";

    if (opts.validReturnValue == null) opts.validReturnValue = true;
    if (opts.message == null) opts.message = "后台校验,数据不合格。";
    if(opts.live==null) opts.live=true;

    var fieldSelect = formSelect.find("[name=" + name + "]:input");
    var  onlineCheck = function(valObj){
        $.ajax({
            url: url,
            type: opts.method,
            cache: true,
            data: $.param(valObj),
            async: false,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                errorTipBox(textStatus + "网络校验请求失败，请联系管理员");
            },
            success: function (data, textStatus) {
                vlt.getFieldElements(name).data("onlineValid-" + name, data.status);
               if(opts.live) vlt.validateField(name);
            }
        });
    };

    if(opts.live){
        fieldSelect.blur(function () {
            var vlt = formSelect.data('bootstrapValidator');
            vlt.validateField(name);
            if (vlt.isValidField(name)) {
                vlt.updateStatus(name, 'VALIDATING');
                var valObj = new Object();
                valObj[name] = fieldSelect.val();
                onlineCheck(valObj);
            }

        });
    }
    var vlt = formSelect.data('bootstrapValidator');
    var callback = vlt.getOptions(name,"callback","callback");

    vlt.addField(name,  {
        validators: {
            callback: {
                callback: function (value, validator) {
                    if(callback!=null ){
                        var rtObj = callback(value, validator);
                        if(rtObj==false || ('object' == typeof rtObj &&　!rtObj.valid) ) return rtObj;
                    }
                    if(!opts.live){
                        var valObj = new Object();
                        valObj[name] =value;
                        onlineCheck(valObj);
                    }
                    var field = validator.getFieldElements(name);
                    var serviceVal =field.data("onlineValid-"+name);
                    var status =field.data('bv.result.callback');
                    var isValid=true;
                    if(status=='VALIDATING' && serviceVal!=null && serviceVal!=opts.validReturnValue) isValid = false;
                    //重新赋值
                    field.removeData("onlineValid-"+name);
                    return {
                        valid: isValid,
                        message: opts.message
                    };
                }
            }
        }
    });

}


/**
 * 文件上传
 * opt.progressSelector 进度
 * opt.complete
 * opt.success function (data, status)
 * opt.error function (data, status, e)
 */
function uploadFile(fileInputId,opt) {

    $.ajaxFileUpload(
        {
            url: '/file/upload?type=image', //用于文件上传的服务器端请求地址
            secureuri: false,           //一般设置为false
            fileElementId: fileInputId, //文件上传控件的id属性  <input type="file" id="file" name="file" /> 注意，这里一定要有name值
            //data:$("form").serialize(),表单序列化。指把所有元素的ID，NAME 等全部发过去
            dataType: 'json',//返回值类型 一般设置为json
            complete: opt.complete,//只要完成即执行，最后执行
            success: opt.success,  //服务器成功响应处理函数
            error: function (data, status, e){
                //服务器响应失败处理函数
                if(opt.error) opt.error(data, status, e);
                if(opt.progressSelector!=null){
                    clearInterval(progressInterval);
                }
            }
        }
    );
    if(opt.progressSelector!=null) var progressInterval =updateFileUploadProgress(opt.progressSelector,"#"+fileInputId);
}
/**
 * 更新上传文件进度条
 * @param selector
 * @param fileSelector
 */
function updateFileUploadProgress(selector,fileSelector) {
    selector = $(selector);
    var progressId = $(fileSelector).attr("progressId");
    var progressInterval =setInterval(function () {
        $.ajax({
            cache: true,
            type: "post",
            url: "/file/progress",
            data: "progressId=" + progressId,
            async: true,
            success: function (data, textStatus) {
                var $prsBar =  selector.find(".progress-bar");
                var progressValue = parseFloat(data.progress).toFixed(2);
                var progress = progressValue+'%';
                $prsBar.css("width",progress);
                if(100<=progressValue) {
                    progress += "文件上传完成";
                    $prsBar.text(progress);
                    selector.removeClass("active");
                    clearInterval(progressInterval);
                }
                $prsBar.text(progress);
            }
        });
    },1000);
    return progressInterval;
}

/********************************表单处理相关end************************************************/


/********************************工具函数begin************************************************/

/**
 *
 * 获取当前时间,返回字符串形式 yyyy/MM/dd - hh:ii
 */
function getCurrentDate() {
    function p(s) {
        return s < 10 ? '0' + s : s;
    }

    var myDate = new Date();
    //获取当前年
    var year = myDate.getFullYear();
    //获取当前月
    var month = myDate.getMonth() + 1;
    //获取当前日
    var date = myDate.getDate();
    var h = myDate.getHours();       //获取当前小时数(0-23)
    var m = myDate.getMinutes();     //获取当前分钟数(0-59)
    var s = myDate.getSeconds();
    var now = year + '-' + p(month) + "-" + p(date) + " " + p(h) + ':' + p(m) + ":" + p(s);
    return now;
}

function showWH(){
    var s = "";
    s += "网页可见区域宽度："+document.body.clientWidth;
    s += "\n网页可见区域高度："+document.body.clientHeight;
    s += "\n网页可见区域宽度（包括边线）："+document.body.offsetWidth;
    s += "\n网页可见区域高度（包括边线）："+document.body.offsetHeight;
    s += "\n网页正文宽度："+document.body.scrollWidth;
    s += "\n网页正文高度："+document.body.scrollHeight;
    s += "\n屏幕可用工作区域宽度："+window.screen.availWidth;
    s += "\n屏幕可用工作区域高度："+window.screen.availHeight;
    s += "\n屏幕分辨率宽度："+window.screen.width;
    s += "\n屏幕分辨率高度："+window.screen.height;
    console.log(s);
}
/********************************工具函数end************************************************/

function refreshVerifyCode(select,p) {
    $(select).attr("src","/captcha.jpg?p="+p+"&"+Math.random());
}